<template>
  <div class="updata-photo">
    <img :src="img" ref="photo" />
    <div class="inner">
      <div class="quxiao" @click="$emit('delPhoto')">取消</div>
      <div class="queding" @click="confirm">确定</div>
    </div>
  </div>
</template>

<script>
import "cropperjs/dist/cropper.css";
import Cropper from "cropperjs";
import { emitPhoto } from "@/api/user.js";
export default {
  data() {
    return {
      // 创建一个 图片裁剪的实例
      cropper: null,
    };
  },
  props: {
    img: {
      type: String,
      required: true,
    },
  },
  mounted() {
    const image = this.$refs.photo;
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: "move",
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true,
    });
  },
  methods: {
    // 确定上传获取参数
    confirm() {
      this.cropper.getCroppedCanvas().toBlob((blob) => {
        this.onSubmit(blob);
      });
    },
    // 上传函数
    async onSubmit(blob) {
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
      });
      try {
        const formData = new FormData();
        formData.append("photo", blob);
        console.log(blob);
        console.log(formData);
        const { data: res } = await emitPhoto(formData);
        this.$toast.success("修改成功");
        this.$emit("delPhoto", true);
      } catch (error) {
        this.$toast.fail("修改失败");
      }
    },
  },
};
</script>


<style lang="less" scoped>
.updata-photo {
  height: 100%;
  background-color: #000;

  img {
    max-width: 100%;
    display: block;
  }
  .inner {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    justify-content: space-between;
    div {
      width: 90px;
      height: 90px;
      font-size: 30px;
      color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>